const crypto = require("crypto");
const config = {
  dir: 'hzlablum', // 上传目录
  bucket: 'hzlablum',// Bucket 名称
  region: 'oss-cn-guangzhou',// OSS 所在的 Region
  accessKeyId: 'LTAI4GKjFCsr7br68bRU6MNT',// 安全受限的 Access key ID
  accessKeySecret: 'T8rOYl2yx6HVLcGRfHGg1XC6LnJ4OF',// Access key secret
  expAfter: 3600000, // 签名失效时间，毫秒
  maxSize: 1048576000 // 文件最大尺寸
};

module.exports = (callback) => {
  let host = `https://${config.bucket}.${config.region}.aliyuncs.com`;
  let expireTime = new Date().getTime() + config.expAfter;
  let expiration = new Date(expireTime).toISOString();
  let policyString = JSON.stringify({
    'expiration': expiration,
    'conditions': [
      ['content-length-range', 0, config.maxSize],
      ['starts-with', '$key', config.dir]
    ]
  });
  let policy = Buffer.from(policyString).toString('base64');
  let signature = crypto.createHmac('sha1', config.accessKeySecret).update(policy).digest("base64");
  let tokenData = {
    'signature': signature,
    'policy': policy,
    'host': host,
    'accessid': config.accessKeyId,
    'expire': expireTime,
    'dir': config.dir
  };
  let responseObject = {
    isBase64Encoded: true,
    statusCode: 200,
    headers: {
      "Content-type": "application/json; charset=utf-8"
    },
    tokenData,
    body: Buffer.from(JSON.stringify(tokenData)).toString("base64")
  };
  callback(responseObject);
}